package com.tosit.bmx.common.shiro;

import com.tosit.bmx.domian.Muser;
import com.tosit.bmx.domian.User;
import com.tosit.bmx.service.admin.MuserService;
import com.tosit.bmx.service.user.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;

/**
 * 用户后台验证
 *
 * @author tsl
 * @create 2018-04-20 9:48
 **/
public class UserVerifyShiro extends AuthorizingRealm {
    @Autowired
    UserService userService;
    @Autowired
    MuserService muserService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        CustomizedToken customizedToken = (CustomizedToken) authenticationToken;
        String loginType = customizedToken.getLoginType();
        String name = customizedToken.getUsername();
        SimpleAuthenticationInfo simpleAuthenticationInfo = null;
        if (loginType.equals("User")) {
            User user = userService.findsUserByName(name);
            if (user == null) {
                // 用户名不存在抛出异常
                throw new UnknownAccountException();
            } else {
                if (user.getStatus() == 0) {
                    throw new BanException();
                }
                if (user.getTimelimit() != null && !user.getTimelimit().equals("")) {
                    int curruntTime = (int) (new Date().getTime() / 1000);
                    if (curruntTime > Integer.valueOf(user.getTimelimit().trim())) {
                        throw new ExpireException();
                    }
                }
                simpleAuthenticationInfo = new SimpleAuthenticationInfo(user, user.getPassword(), this.getName());
            }
            return simpleAuthenticationInfo;
        } else {
            Muser muser = muserService.findsUserByName(name);
            if (muser == null) {
                // 用户名不存在抛出异常
                throw new UnknownAccountException();
            } else {
                simpleAuthenticationInfo = new SimpleAuthenticationInfo(muser, muser.getMpass(), this.getName());
            }
            return simpleAuthenticationInfo;
        }

    }
}
